package cn.itcast.service.impl;

import cn.itcast.dao.AreaRepository;
import cn.itcast.dao.FixedAreaRepository;
import cn.itcast.dao.OrderRepository;
import cn.itcast.dao.WorkBillRepository;
import cn.itcast.domain.base.Area;
import cn.itcast.domain.base.Courier;
import cn.itcast.domain.base.FixedArea;
import cn.itcast.domain.base.SubArea;
import cn.itcast.domain.constant.Constants;
import cn.itcast.domain.delivery.Order;
import cn.itcast.domain.delivery.WorkBill;
import cn.itcast.service.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.ws.rs.core.MediaType;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

@Service("orderServiceImpl")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private FixedAreaRepository fixedAreaRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private WorkBillRepository workBillRepository;

    @Override
    @Transactional
    public void saveOrder(Order order) {
        //在orderService进行订单分单业务处理
        //设置订单基础信息
        order.setOrderTime(new Date());//下单时间
        order.setOrderNum(UUID.randomUUID().toString().replace("-",""));//订单号
        //基于crm地址匹配进行分单 @Path("/customer/getfixedareaid/{address}")
        String fixedAreaId = WebClient.create(Constants.CRM_HOST + Constants.CRM_URL + "/services/customerService/customer/getfixedareaid/" + order.getSendAddress())
                .accept(MediaType.APPLICATION_JSON).get(String.class);
        if (fixedAreaId != null) {
            //不为空 进行分单处理
            FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);//获取相关分区信息
            Courier courier = fixedArea.getCouriers().iterator().next();//查询该分区快递员
            if (courier != null) {

                saveOrder(order, courier);
                //生成订单 发送短信 通知快递员进行取件

                return ;
            }
        }
        //基于分区关键字进行匹配
        Area sendArea = order.getSendArea();
        Area area = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(), sendArea.getCity(), sendArea.getDistrict());
        order.setSendArea(area);//将持久化对象保存
        Area recArea = order.getRecArea();
        Area recarea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(), recArea.getDistrict());
        order.setRecArea(recarea);
        //对area进行非空判断 实际生活总不需要这个判断 不存在未被快递公司定义的区域
        if (area != null) {
            for (SubArea subArea : area.getSubareas()) {
                //判断当前客户下单地址是否包含该地区关键字
                if (order.getSendAddress().contains(subArea.getKeyWords())) {
                    //找到分区 关联订单
                    Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                    while (iterator.hasNext()){
                       Courier courier=iterator.next();
                        if (courier != null) {
                            saveOrder(order, courier);

                            System.out.println("使用activeMQ发送短信");
                            return ;
                        }

                    }

                }

            }
            for (SubArea subArea : area.getSubareas()) {
                //判断当前客户下单地址是否包含该地区关键字
                if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
                    //找到分区 关联订单
//                    Courier courier = subArea.getFixedArea().getCouriers().iterator().next();
                    Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
                    if(iterator.hasNext()){
                        Courier courier = iterator.next();
                        if (courier != null) {
                            saveOrder(order, courier);
                            //生成订单 发送短信 通知快递员进行取件
                            System.out.println("使用activeMQ发送短信");
                            return ;
                        }
                    }

                }
            }

        } //生成人工订单 发送短信
        order.setOrderType("2");//人工生成订单
        generateWorkBill(order);
        return ;
    }

    @Override
    //根据orderNum查询运单信息完成页面数据回显
    public Order findOrderByNum(String orderNum) {
        return orderRepository.findByOrderNum(orderNum);
    }


    private void generateWorkBill(Order order) {
        //生成人工订单 保存人工订单
        WorkBill workBill = new WorkBill();
        workBill.setType("新");
        workBill.setPickstate("新单");
        workBill.setBuildtime(new Date());
        workBill.setOrder(order);
        workBill.setRemark(order.getRemark());
        final String smsNumber = RandomStringUtils.randomNumeric(4);
        workBill.setSmsNumber(smsNumber);
        workBill.setCourier(order.getCourier());
        //发送短信提醒 保存订单
        System.out.println("使用activeMQ发送短信");
        orderRepository.save(order);
        workBillRepository.save(workBill);

    }

    private void saveOrder(Order order, Courier courier) {
        //分单成功 将订单信息绑定快递员
        order.setCourier(courier);
        //1 代表自动分单
        order.setOrderType("1");
        //将订单保存进数据库
        orderRepository.save(order);
        //生成订单 发送短信 通知快递员进行取件
    }
}